﻿#region changelog
/*
 * 02/04/09 - wbw (Seagull Consulting): Original code
 * 02/20/09 - wbw : TemplateXMLFile and SeriesAliasFile
 * 03/16/09 - wbw : changed code to pull Series Name from TheTVDB rather than from input file name
 */
#endregion

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Durrant.Plugins.TvDB;
using Durrant.Plugins;
using System.Threading;

namespace SeagullConsulting.TvDBReader
{
    public partial class MainForm : Form
    {
        private string extractionRegex = Constants.EXTRACTION_REGEX;
        private string defaultDir = String.Empty;
        private string templateXMLFileName = string.Empty;
        private bool readingTvDB = false;
        Series series;
        Episode episode;

        public MainForm()
        {
            InitializeComponent();
            LoadSettings();
        }

        private void buttonReadTvDB_Click(object sender, EventArgs e)
        {
            //See if we are already reading TvDB, if so then wait till done
            if (readingTvDB != true)
            {
                Match m;
                string seriesXML = string.Empty;
                string episodeXML = string.Empty;
                readingTvDB = true;

                if (textBoxFileName.Text.Length > 0)
                {
                    series = new Series();
                    episode = new Episode();
                    m = Regex.Match(textBoxFileName.Text, extractionRegex);

                    //Parse Filename and store results
                    series.fileName = m.Groups["series"].Value;
                    episode.Season = m.Groups["season"].Value;
                    episode.Nbr = m.Groups["episodenbr"].Value;
                    labelSeriesName.Text = series.Name;
                    labelSeason.Text = episode.Season;
                    labelEpisodeNbr.Text = episode.Nbr;

                    //Retrieve Series info and display
                    if (TVDB.setSeriesId(series.getURLName()))
                    {
                        seriesXML = TVDB.getSeriesXMLById();
                        if (seriesXML.Length != 0)
                        {
                            textBoxSeriesXML.Text = seriesXML;
                            series.Id = TVDB.SeriesId;
                            labelSeriesId.Text = series.Id;
                            series.parse(seriesXML);
                            labelSeriesName.Text = series.SeriesName;
                            labelSeriesDayOfWeek.Text = series.DayOfWeek;
                            labelSeriesAirTime.Text = series.AirTime;
                            labelSeriesContentRating.Text = series.ContentRating;
                            labelSeriesGenre.Text = series.Genre;
                            labelSeriesNetwork.Text = series.Network;
                            labelSeriesRunTime.Text = series.RunTime;
                            textBoxSeriesOverview.Text = series.Overview;

                            //Retrieve Episode info and display
                            episodeXML = TVDB.getEpisodeXML(episode.Season, episode.Nbr);
                            if (episodeXML.Length != 0)
                            {
                                episode.parse(episodeXML);
                                labelEpisodeId.Text = episode.Id;
                                labelFirstAirDate.Text = episode.FirstAired;
                                labelEpisodeName.Text = episode.Name;
                                textBoxEpisodeOverview.Text = episode.Overview;
                                textBoxEpisodeXML.Text = episodeXML;
                                buttonGenerateXML.Enabled = true;
                            }
                            else
                                MessageBox.Show("Unable to find Episode in TvDB Database.", "Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                            MessageBox.Show("Unable to find Series in TvDB Database.", "Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                //Okay to let user Click on Read button again
                readingTvDB = false;
            }
        }

        private void buttonGenerateXML_Click(object sender, EventArgs e)
        {
            SageXMLFile sageFile = new SageXMLFile();
            DialogResult result;

            if (File.Exists(defaultDir + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(textBoxFileName.Text) + Constants.MPG_FILE_EXT + Constants.XML_FILE_EXT))
            {
                result = MessageBox.Show("XML File already exists.  Do you want to overwrite it?", "File Exists", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    //expects file name will equal full path + filename .mpg.xml extension
                    if (sageFile.create(defaultDir + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(textBoxFileName.Text) + Constants.MPG_FILE_EXT + Constants.XML_FILE_EXT, series, episode))
                        MessageBox.Show("XML file created", "File Created", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    else
                        MessageBox.Show("Unable to create XML file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }
                else
                    MessageBox.Show("XML file not overwritten", "File Created", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                //expects file name will equal full path + filename .mpg.xml extension
                if (sageFile.create(defaultDir + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(textBoxFileName.Text) + Constants.MPG_FILE_EXT + Constants.XML_FILE_EXT, series, episode))
                    MessageBox.Show("XML file created", "File Created", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                    MessageBox.Show("Unable to create XML file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }
        
        private void buttonOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

			openFileDialog.InitialDirectory = defaultDir;
			openFileDialog.Filter = Constants.FILE_DIALOG_FILTER ;
			openFileDialog.RestoreDirectory = true ;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                textBoxFileName.Text = Path.GetFileName(openFileDialog.FileName);
                defaultDir = Path.GetDirectoryName(openFileDialog.FileName);
            }

        }

        private void LoadSettings()
        {
            //Force application to read from config file.
            TVDB.APIKey = Properties.Settings.Default.APIKey;
            TVDB.TemplateXMLFileName = Properties.Settings.Default.TemplateXMLFileName;
            TVDB.SeriesAliasFileName = Properties.Settings.Default.SeriesAliasFileName;
            TVDB.init();
            defaultDir = Properties.Settings.Default.DefaultDir;
            templateXMLFileName = TVDB.TemplateXMLFileName;
        }

    } //end of Class
} //end of namespace
